package com.xueyi.game.backend.service.impl;

import com.xueyi.core.utils.LogUtil;
import com.xueyi.game.backend.config.BaseSqlConfig;
import com.xueyi.game.backend.config.GatewayConfig;
import com.xueyi.game.backend.entity.dto.*;
import com.xueyi.game.backend.entity.po.BaseRole;
import com.xueyi.game.backend.entity.po.BaseRoleJoinAuthority;
import com.xueyi.game.backend.entity.po.BaseUser;
import com.xueyi.game.backend.entity.vo.BaseSelectVo;
import com.xueyi.game.backend.entity.vo.FindRoleListVo;
import com.xueyi.game.backend.mapper.BaseRoleMapper;
import com.xueyi.game.backend.service.IBackendRoleService;
import com.xueyi.game.backend.utils.BaseUserUtil;
import com.xueyi.starter.utils.FinalUtil;
import com.xueyi.starter.utils.JedisUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @authoer: hxs
 * @createDate: 2022/11/9 09:39
 * @description: 角色管理业务
 */
@Service
@AllArgsConstructor
@Slf4j
public class BackendRoleServiceImpl implements IBackendRoleService {
    private final BaseRoleMapper roleMapper;

    private final BaseSqlConfig baseSqlConfig;
    private final JedisUtil jedisUtil;
    private final BaseUserUtil baseUserUtil;
    private final LogUtil logUtil;

    /**
     * 获取角色列表
     *
     * @param findRoleListReq
     * @return
     * @author hxs
     */
    @Override
    public FindRoleListVo findRoleList(FindRoleListDto findRoleListReq) {
        //校验参数
        findRoleListReq.format();
        findRoleListReq.countStartIndex();

        List<BaseRole> list = new ArrayList<>();
        //获取总条数
        Integer total = roleMapper.findRoleListTotal(findRoleListReq.getRoleName(), findRoleListReq.getIsValid(),
                baseSqlConfig.getRoleTableName());

        //总条数大于0是才查询列表
        if (total > 0) {
            list = roleMapper.findRoleList(findRoleListReq.getRoleName(), findRoleListReq.getIsValid(),
                    findRoleListReq.getStartIndex(), findRoleListReq.getLimit(), baseSqlConfig.getRoleTableName());
        }

        //封装返回对象
        FindRoleListVo response = new FindRoleListVo();
        response.setRoleList(list);
        response.setTotal(total);
        return response;
    }

    /**
     * 新增角色
     *
     * @param addOrUpdateRoleReq
     * @return
     * @author hxs
     */
    @Override
    public void addRole(AddOrUpdateRoleDto addOrUpdateRoleReq) {
        //封装参数
        BaseRole role = new BaseRole();
        role.setRoleName(addOrUpdateRoleReq.getRoleName().trim());
        role.setIsValid(1);

        //新增角色
        roleMapper.addRole(role, baseSqlConfig.getRoleTableName());
        logUtil.info("新增角色：{}", role.getRoleName());

        BaseUser user = GatewayConfig.USER_LOCAL.get();
        baseUserUtil.saveLog(user.getId() + "", "【角色管理】用户：" + user.getuName() + " 新增了角色 " + addOrUpdateRoleReq.getRoleName());

    }

    /**
     * 修改角色
     *
     * @param addOrUpdateRoleReq
     * @return
     * @author hxs
     */
    @Override
    public void updateRole(AddOrUpdateRoleDto addOrUpdateRoleReq) {
        //封装参数
        BaseRole role = new BaseRole();
        role.setId(addOrUpdateRoleReq.getId());
        role.setRoleName(addOrUpdateRoleReq.getRoleName().trim());

        //修改角色
        roleMapper.updateRole(role, baseSqlConfig.getRoleTableName());
        logUtil.info("修改角色{}：{}", role.getId(), role.getRoleName());

        BaseUser user = GatewayConfig.USER_LOCAL.get();
        baseUserUtil.saveLog(user.getId() + "", "【角色管理】用户：" + user.getuName() + " 修改了角色 " + addOrUpdateRoleReq.getId() + " 的信息");

    }

    /**
     * 修改角色的状态
     *
     * @param changeRoleStatusReq
     * @return
     * @author hxs
     */
    @Override
    public void changeRoleStatus(ChangeRoleStatusDto changeRoleStatusReq) {
        //对角色状态取反
        if (changeRoleStatusReq.getIsValid().equals(1)) {
            changeRoleStatusReq.setIsValid(0);
        } else {
            changeRoleStatusReq.setIsValid(1);
        }

        //修改角色状态
        roleMapper.changeRoleStatus(changeRoleStatusReq, baseSqlConfig.getRoleTableName());
        logUtil.info("修改了角色{}的状态为：{}", changeRoleStatusReq.getId(), changeRoleStatusReq.getIsValid());

        BaseUser user = GatewayConfig.USER_LOCAL.get();
        if (changeRoleStatusReq.getIsValid().equals(1)) {
            baseUserUtil.saveLog(user.getId() + "", "【角色管理】用户：" + user.getuName() + " 修改了角色 " + changeRoleStatusReq.getId() + " 状态为正常 ");
        } else {
            baseUserUtil.saveLog(user.getId() + "", "【角色管理】用户：" + user.getuName() + " 修改了角色 " + changeRoleStatusReq.getId() + " 状态为禁用 ");
        }


        //删除缓存
        removeCacheAfterChangeRole(String.valueOf(changeRoleStatusReq.getId()));


    }

    /**
     * 为角色关联权限
     *
     * @param bindJurisdictionForRoleReq
     * @author hxs
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindJurisdictionForRole(BindJurisdictionForRoleDto bindJurisdictionForRoleReq) {
        //校验参数
        bindJurisdictionForRoleReq.format();

        //通过角色id删除所有该角色当前所有的权限
        roleMapper.relieveJurisdictionByRoleId(bindJurisdictionForRoleReq.getRoleId(), baseSqlConfig.getAuthorityTableName());


        //如果权限列表不为空则批量插入到数据库
        if (!StringUtils.isBlank(bindJurisdictionForRoleReq.getJurisdictionId())) {
            String[] jurisdictionIds = bindJurisdictionForRoleReq.getJurisdictionId().split(",");
            //封装参数
            List<BaseRoleJoinAuthority> list = new ArrayList<>();
            for (String id : jurisdictionIds) {
                BaseRoleJoinAuthority item = new BaseRoleJoinAuthority();
                item.setRoleId(bindJurisdictionForRoleReq.getRoleId());
                item.setMenuId(Integer.parseInt(id));
                list.add(item);
            }

            //批量插入到数据库
            roleMapper.bindJurisdictionByRoleId(list, baseSqlConfig.getAuthorityTableName());
            logUtil.info("为角色 {} 关联了权限 {}", bindJurisdictionForRoleReq.getRoleId(), bindJurisdictionForRoleReq.getJurisdictionId());

            //删除缓存
            removeCacheAfterChangeRole(String.valueOf(bindJurisdictionForRoleReq.getRoleId()));
        }

        BaseUser user = GatewayConfig.USER_LOCAL.get();
        baseUserUtil.saveLog(user.getId() + "", "【角色管理】用户：" + user.getuName() + " 修改了角色 " + bindJurisdictionForRoleReq.getRoleId() + " 的权限为 " + bindJurisdictionForRoleReq.getJurisdictionId());


    }

    /**
     * 在修改完角色后清空缓存
     *
     * @param roleIds 角色id
     * @author hxs
     */
    // private void removeCacheAfterChangeRole(Integer roleId) {
    //     //获取绑定了该角色的用户
    //     List<Integer> userIdList = roleMapper.findUserByRoleId(roleId, baseSqlConfig.getUserJoinRoleTableName());
    //     Jedis jedis = null;
    //     try {
    //         jedis = jedisUtil.getJedis();
    //         for (Integer userId : userIdList) {
    //             jedis.del("EDU_SYSTEM_ADMIN_LEFT_MENU:" + userId);
    //         }
    //     } finally {
    //         FinalUtil.unLockAndCloseRedis(jedis);
    //     }
    //
    // }
    @Override
    public void removeCacheAfterChangeRole(String roleIds) {
        //获取绑定了该角色的用户
        List<Integer> userIdList = roleMapper.findUserByRoleId(roleIds, baseSqlConfig.getUserJoinRoleTableName());
        if (CollectionUtils.isEmpty(userIdList)) {
            return;
        }
        Jedis jedis = null;
        try {
            jedis = jedisUtil.getJedis();
            for (Integer userId : userIdList) {
                jedis.del("EDU_SYSTEM_ADMIN_LEFT_MENU:" + userId);
            }
        } finally {
            FinalUtil.unLockAndCloseRedis(jedis);
        }

    }

    /**
     * 通过角色id获取该角色的权限id列表
     *
     * @param findJurisdictionListByRoleIdReq
     * @return
     * @author hxs
     */
    @Override
    public String findJurisdictionListByRoleId(FindJurisdictionListByRoleIdDto findJurisdictionListByRoleIdReq) {
        String ids = roleMapper.findJurisdictionListByRoleId(findJurisdictionListByRoleIdReq.getRoleId(), baseSqlConfig.getAuthorityTableName());
        ids = StringUtils.isBlank(ids) ? "" : ids.trim();
        return ids;
    }

    /**
     * 获取所有的角色（下拉菜单用）
     *
     * @return
     * @author hxs
     */
    @Override
    public List<BaseSelectVo> findAllRoleSelectVo() {
        return roleMapper.findAllRoleSelectVo(baseSqlConfig.getRoleTableName());
    }
}
